package leets.leet224;

import java.util.ArrayDeque;
import java.util.Deque;

public class Solution {
    public int calculate(String s) {
        Deque<Integer> ops=new ArrayDeque<>();
        ops.add(1);
        int ret=0;
        int sign=1;
        int n=s.length();



        int i=0;
        while (i<n){
            if (s.charAt(i)==' '){
                i++;
            }else if (s.charAt(i)=='+'){
                sign=ops.peek();
                i++;
            }else if (s.charAt(i)=='-'){
                sign=-ops.peek();
                i++;
            }else if (s.charAt(i)=='('){
                ops.push(sign);
                i++;
            }else if (s.charAt(i)==')'){
                ops.pop();
                i++;
            }else {
                long num=0;
                while (i<n&&Character.isDigit(s.charAt(i))){
                    num=num*10+s.charAt(i)-'0';
                    i++;
                }
                ret+=sign*num;

            }
        }
        return ret;
    }



}
